package com.example.taobaolianmeng.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaolianmeng.R;
import com.example.taobaolianmeng.base.BaseFragment;
import com.example.taobaolianmeng.model.domain.Categories;
import com.example.taobaolianmeng.model.domain.HomePagerContent;
import com.example.taobaolianmeng.model.domain.IBaseInfo;
import com.example.taobaolianmeng.model.domain.TicketResult;
import com.example.taobaolianmeng.presenter.ICategoryPagerPresenter;
import com.example.taobaolianmeng.presenter.ITicketPresenter;
import com.example.taobaolianmeng.ui.activity.TicketActivity;
import com.example.taobaolianmeng.ui.adapter.HomePageContentAdapter;
import com.example.taobaolianmeng.ui.adapter.LooperPagerAdapter;
import com.example.taobaolianmeng.ui.custom.AutoLoopViewPager;
import com.example.taobaolianmeng.utils.Constants;
import com.example.taobaolianmeng.utils.PresenterManger;
import com.example.taobaolianmeng.utils.SizeUtils;
import com.example.taobaolianmeng.utils.TicketUtil;
import com.example.taobaolianmeng.utils.ToastUtils;
import com.example.taobaolianmeng.view.ICategoryPagerCallback;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.views.TbNestedScrollView;

import java.util.List;

import butterknife.BindView;

public class HomePagerFragment extends BaseFragment implements ICategoryPagerCallback, HomePageContentAdapter.OnListItemClickListener, LooperPagerAdapter.OnLooperPageItemClickListener {

    private static final String TAG = "HomePagerFragment";
    private ICategoryPagerPresenter mPagerPresenter;
    private int mMaterialId;
    private HomePageContentAdapter mContentAdapter;
    private LooperPagerAdapter mLooperPagerAdapter;

    public static HomePagerFragment newInstance(Categories.DataBean category){
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        //
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE,category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID,category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;

    @BindView(R.id.looper_pager)
    public AutoLoopViewPager looperPager;

    @BindView(R.id.home_pager_title)
    public TextView currentCategoryTv;

    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;

    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout twinklingRefreshLayout;

    @BindView(R.id.home_pager_parent)
    public LinearLayout homePagerParent;

    @BindView(R.id.home_pager_header_container)
    public LinearLayout homeHeaderContainer;



    @BindView(R.id.home_pager_nested_scroller)
    public TbNestedScrollView homePagerNestedView;



    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }

    @Override
    public void onResume() {
        super.onResume();
        //可见调用轮播
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        looperPager.stopLoop();
    }

    //添加banner滑动共功能
    @Override
    protected void initListener() {
        mContentAdapter.setOnListItemClickListener(this);
        mLooperPagerAdapter.setOnLooperPageItemClickListener(this);

        //监听滑动banner
        looperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mLooperPagerAdapter.getDataSize() ==0) {
                    return;
                }
//                Log.d(TAG,"position-->"+position);
                int targetPosition = position % mLooperPagerAdapter.getDataSize();
//                Log.d(TAG,"targetPosition->"+targetPosition);
                //切换指示器
                updateLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //监听刷新事件
        twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                Log.d(TAG,"触发load more");
                //加载更多
                if (mPagerPresenter != null) {
                    mPagerPresenter.loaderMore(mMaterialId);
                }
            }
            //TODO
//            @Override
//            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
//                super.onRefresh(refreshLayout);
//            }
        });
        //拿到推荐text高度
        currentCategoryTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int measuredHeight = mContentList.getMeasuredHeight();
                Log.d(TAG,"measuredHeight->"+measuredHeight);
            }
        });
        //通过动态设置recycleView的高度来防止频繁创建适配器影响性能
        homePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //拿到滚动高度
                if (homeHeaderContainer==null) {
                    return;
                }
                int headerHeight = homeHeaderContainer.getMeasuredHeight();
                Log.d(TAG,"headerHeight->"+headerHeight);
                homePagerNestedView.setHeaderHeight(headerHeight);

                int measuredHeight = homePagerParent.getMeasuredHeight();
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();
//                Log.d(TAG,"layoutParams.height->"+layoutParams.height);
                Log.d(TAG,"measuredHeight->"+measuredHeight);
                layoutParams.height =measuredHeight;
                mContentList.setLayoutParams(layoutParams);
                if (measuredHeight!=0) {
                    homePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

    }

    private void updateLooperIndicator(int targetPosition) {
        for(int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View point = looperPointContainer.getChildAt(i);
            if(i == targetPosition) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
        }
    }

    @Override
    protected void initView(View rootView) {
        //设置布局管理器
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top =8;
                outRect.bottom =8;
            }
        });

        //创建list适配器
        mContentAdapter = new HomePageContentAdapter();
        //设置适配器
        mContentList.setAdapter(mContentAdapter);
        //创建轮播图适配器
        mLooperPagerAdapter = new LooperPagerAdapter();
        //设置适配器
        looperPager.setAdapter(mLooperPagerAdapter);
        //设置轮播图速度
        looperPager.setDuration(5000);
        //设置Refresh相关内容
        twinklingRefreshLayout.setEnableRefresh(true);
        twinklingRefreshLayout.setEnableLoadmore(true);
//        twinklingRefreshLayout.setBottomView();
    }

    @Override
    protected void initPresenter() {
        mPagerPresenter = PresenterManger.getInstance().getCategoryPagePresenter();
        mPagerPresenter.registerViewCallback(this);

    }

    @Override
    protected void loadData() {
        Bundle arguments = getArguments();
        String title = arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialId = arguments.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        //加载数据
        Log.d(TAG,"title->"+title);
        Log.d(TAG,"materialId->"+ mMaterialId);
        if (mPagerPresenter !=null) {
            mPagerPresenter.getContentByCategoryId(mMaterialId);
        }
        if (currentCategoryTv != null) {
            currentCategoryTv.setText(title);
        }
    }

    @Override
    public void onContentLoaded(List<HomePagerContent.DataBean> contents) {
        //数据列表加载
        //更新ui
        mContentAdapter.setData(contents);
        setupState(State.SUCCESS);

    }

    @Override
    public int getCategoryId() {
        return mMaterialId;
    }

    @Override
    public void onNetworkError() {
        //网络错误
        setupState(State.ERROR);
    }

    @Override
    public void onLoading() {
        setupState(State.LOADING);
    }


    @Override
    public void onEmpty() {
        setupState(State.EMPTY);
    }

    @Override
    public void onLoadMoreError() {
        if (twinklingRefreshLayout != null) {
            ToastUtils.showToast("网络异常，请稍后再试");
        }
    }

    @Override
    public void onLoadMoreEmpty() {
        if (twinklingRefreshLayout != null) {
            ToastUtils.showToast("滑到底了");
        }
    }

    @Override
    public void onLoaderMoreLoaded(List<HomePagerContent.DataBean> contents) {
        //添加到适配器数据底部
        mContentAdapter.addData(contents);
        if (twinklingRefreshLayout != null) {
            twinklingRefreshLayout.finishLoadmore();
        }
        ToastUtils.showToast("加载了"+contents.size()+"记录");

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onLooperListLoaded(List<HomePagerContent.DataBean> contents) {
        //轮播图数据这里返回
        Log.d(TAG,"lopper size -->"+contents.size());
        mLooperPagerAdapter.setData(contents);
        //设置到中间点 中间点%数据size不一定为0，显示就不是第一个
        int dx = (Integer.MAX_VALUE / 2) % contents.size();
        int targetCenterPosition = (Integer.MAX_VALUE / 2) - dx;

        looperPager.setCurrentItem(targetCenterPosition);
        Log.d(TAG,"url --->"+contents.get(0).getPict_url());
        looperPointContainer.removeAllViews();

        //添加点
        for (int i = 0; i < contents.size(); i++) {
            View point = new View(getContext());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(SizeUtils.dip2px(getContext(),8),SizeUtils.dip2px(getContext(),8));
            layoutParams.leftMargin = SizeUtils.dip2px(getContext(),5);
            layoutParams.rightMargin = SizeUtils.dip2px(getContext(),5);
            point.setLayoutParams(layoutParams);
            if(i == 0) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
            looperPointContainer.addView(point);
        }

    }

    @Override
    protected void release() {
        if (mPagerPresenter !=null) {
            mPagerPresenter.unregisterViewCallback(this);
        }
    }

    @Override
    public void onItemClick(IBaseInfo item) {
        TicketUtil.toTicketPage(getContext(),item);

    }

    @Override
    public void onLooperItemClick(IBaseInfo item) {
        //轮播图内容被点击
        Log.d(TAG,"item click ->"+item.getTitle());
    }
}
